/**
 * @file 工单列表
 * @author yangjiangming <449654337@qq.com>
 * @date 2018/11/27 10:20:40
 */
layui.extend({
    oms_work_modify_route: 'work/modify/common/zmn.modify.route'
}).define(['admin',
    'oms_work_modify_route',
    'list_modify_operation', 'oms_common_table_config',
    'element', 'layer', 'form', 'table', '$api',
    'zmnTable', 'lodash', '$http', 'zmnUtils',
    'formSelects', 'zmnSelect', 'zmnOmsSelect', 'oms_work_config'
], function(exports) {
    var $ = layui.$;
    var form = layui.form;
    var layer = layui.layer;
    var table = layui.table;
    var zmnTable = layui.zmnTable;
    var zmnUtils = layui.zmnUtils;
    var operationUtils = layui.list_modify_operation;
    var formSelects = layui.formSelects;
    var workTableConfiger = layui.oms_common_table_config;
    var element = layui.element;
    var $http = layui.$http;
    let zmnOmsSelect = layui.zmnOmsSelect;
    let zmnSelect = layui.zmnSelect;
    var select2;
    var config = layui.oms_work_config;
    var route = layui.oms_work_modify_route;
    var admin = layui.admin

    var tableConfig = workTableConfiger.createTableConfig(tableName);

    var tableInstance = null;
    // 当前操作的工单
    window.currentWork = {};

    let json = {
        vo: {
            limitPermit: false,
            orgLimitPermit: dpermitOrgIdList && dpermitOrgIdList.length > 0 ? true : false, // 没有配置组织架构，不引用权限
            channelLimitPermit: false,
            companyIdOrGirdCompanyIdList: null,
            spCompanyOrGridSpCompanyIdIdList: null,
            companyIdList: null,
            spCompanyIdList: null,
            gridCompanyIdList: null,
            gridSpCompanyIdList: null,
            servCategId: null,
            bizType: defaultBizType,
        }
    };

    // 工单备注
    var WORK_TRACK_REMARK_URL = '/work/ajax/track/remark.action';
    // 跟单日志
    var WORK_TRACK_LOG_URL = '/work/ajax/track/log.action';
    // 跟单列表
    var WORK_TRACK_CURRENT_LOG_LIST_URL = "/track/api/listCurrentLogContentByWorkIdList";

    // 根据城市获取区域 URL
    var AREA_PERMIT_LIST_URL = '/area/permit/county/list.action';
    // 话务工单，不判断权限
    var AREA_LIST_URL = '/area/county/list.action';

    // 根据一级分类获取二级分类 URL
    var CATEGORY_LIST_URL = '/serv/categ/list'; // TODO
    // 多工程师远程查询 URL
    var MASTER_LIST_URL = '/staff/master/list.action';
    // 工程师主管远程查询 URL
    var SUPERVISOR_MASTER_LIST_URL = '/staff/master/supervisor/list.action';
    // 操作员远程查询 URL
    var OPERATOR_LIST_URL = '/staff/staff/company/list.action';
    // 部分下的 操作员远程查询 URL
    var OPERATOR_LIST_WITH_DEPT_ID_URL = '/staff/dept/staff/list.action';
    // 公司远程查询 URL
    var COMPANY_LIST_URL = '/company/list/query.action';

    // 服务公司查询 URL
    var MANAGE_COMPANY_URL = '/company/mult/manage/company/list.action';
    // 渠道列表URL
    var CHANNEL_PERMIT_LIST_URL = '/channel/permit/list/query?';
    var CHANNEL_LIST_URL = '/channel/list/query?';
    // 一级渠道列表URL
    var CHANNEL_ONE_LIST_URL = '/channel/one/permit/list/query?';
    // 产品分组
    var SERV_PRODUCT_GROUP_URL = '/serv/product/group/list.action';
    // 取消缘由
    var CANCEL_REASON_LIST_URL = '/common/cancelReason/list.action';


    // 店铺列表URL
    var SHOP_LIST_URL = '/shop/list/query?';

    var datePickerSelectorArray = [
        'receiveTime', // 接单时间
        'dutyTime', // 预约时间
        'assignConfirmTime', //接单时间
        'distributeTime', // 派单时间
        'visitTime', // 上门时间
        'takerTime', // 领单时间
        'completeTime', // 收单时间
        'checkoutTime', // 收单时间
        'accountTime', // 算账时间
        'replyVisitTime', // 回访时间
        'partReimburseTime', // 配件报销时间
        'refundAmountTime', // 退款时间
        'cancelTime', // 取消时间
        'nextContactTime', //联系时间
        'masterReviewTime', // 工程师审核时间
        'platReviewTime', // 后台审核
        'commentTime', // 评价时间
        'signInTime', // 签到时间
        'verificationTime', // 核销时间
        'signForTime', // 签收时间
        'serviceCompleteTime', // 服务完成时间
        'suspendTime', // 挂起时间
        'channelStatementCanTime' // 渠道可结算时间
    ];

    var multipleSelectNameArray = [
        'cityIdList',
        'provinceIdList',
        'countyIdList',
        'workStatusList',
        'workCancelStatusList',
        'cancelerTypeList',
        'trackTypeId',
        'showCategOneIdList',
        'showCategTwoIdList',
        'showProductIdList',
        'categOneIdList',
        'categTwoIdList',
        'productIdList',
        'channelIdList',
        'channelTwoIdList',
        'sourceChannelIdList',
        'sourceChannelTwoIdList',
        'failMapIdList',
        'servProductGroupIdList',
        'companyIdOrGridCompanyIdList',
        'companyIdList',
        'gridCompanyIdList',
        'gridIdList',
        'tagIdList',
        'payStatusList',
        'refundWorkReviewStatusList',
        'compensateWorkReviewStatusList',
        'partakeQuotationTypeList',
        'orderPostStatusList',
        'workTypeList',
        'manageCompanyIdOrGridManageCompanyIdList',
        'manageCompanyIdList',
        'gridManageCompanyIdList'
    ];

    /**
     * 搜索下拉框
     */
    let selectSearch = {
        /**
         * 服务商搜索下拉框
         *
         * @param params  参数包含：
         * {
         *     plat: 平台,
         *     isRadio: 是否单选 (不填默认为false),
         *     subCompanyId: 子公司下拉框id,
         *     manageCompanyId: 服务商下拉框id
         *  }
         *
         * @param subCompanyCallBack
         * @param manageCompanyCallBack
         */
        subCompanyAndSpCompanySearchInit(params, subCompanyCallBack, manageCompanyCallBack) {

            // 默认值false
            params.isRadio = params.isRadio || false;

            /* 子公司下拉框 */
            if (checkExistId(params.subCompanyId)) {
                zmnSelect.selectSubCompany(params.subCompanyId, {
                    isRadio: params.isRadio,
                    remote: {
                        limitPermit: json.vo.orgLimitPermit,
                        events: {
                            extendParams: function () {
                                return {plat: params.plat}
                            }
                        },
                    },
                    events: {
                        changed: function (values) {
                            console.log("========== 子公司下拉框 =========");
                            console.log("已选中的值:" + values);
                            // 更新指定下拉框的扩展请求参数
                            zmnSelect.updateExtendParamsEvent(params.manageCompanyId, () => {
                                return {
                                    companyId: values.length > 0 ? values[0] : null
                                }
                            });

                            // 执行【子公司下拉框】回调
                            subCompanyCallBack(values);
                            // 清空【服务商】下拉框数据
                            zmnSelect.clearData(params.manageCompanyId)
                            // 远程搜索【服务商】下拉框数据
                            zmnSelect.triggerSearch(params.manageCompanyId)
                        }
                    }
                });
            }

            /* 服务商下拉框 */
            if (checkExistId(params.manageCompanyId)) {
                zmnSelect.searchSpCompany(params.manageCompanyId, {
                    isRadio: params.isRadio,
                    page: {
                        enable: true,  //开关：true-开启；false-关闭
                        pageSize: 50,   //页数
                        isShowEmpty: false, //无数据时是否显示分页
                        remote: true, //远程分页开关：true-开启；false-关闭
                    },
                    remote: {
                        limitPermit: false,
                        events: {
                            validate: function (searchValue) {
                                let prevValues = zmnSelect.getSelectedValue(params.subCompanyId)
                                return zmnUtil.isArray(prevValues) && prevValues.length > 0 ? true : false;
                            },
                            extendParams: function () {
                                return {companyId: null}
                            }
                        },
                    },
                    events: {
                        changed: function (values) {
                            console.log("========== 服务商下拉框 =========");
                            console.log("已选中的值:" + values);
                            // 执行【服务商下拉框】回调
                            manageCompanyCallBack(values)
                        }
                    }
                })
            }

        }
    }

    /**
     * 延迟加载
     * @param func 处理函数
     * @param timeout 延迟时间
     */
    function lazyLoad(func, timeout) {
        setTimeout(func, timeout || 0);
    }

    /**
     * 渲染日期选择器
     * @param selector 日期选择器的选择器或者 Dom 对象
     */
    function renderDatePicker(elem, name) {
        var laydate = this;
        var config = {
            elem: elem,
            format: name.indexOf('Start') !== -1 ? 'yyyy-MM-dd HH:mm:ss' : 'yyyy-MM-dd HH:mm:ss',
            type: 'datetime',
            trigger: 'click'
        };

        var minTime = $(elem).data('min') || defaultMinTime;
        if (minTime) {
            config.min = minTime;
        }
        laydate.render(config);
    }

    /**
     * 初始化页面的所有日期组件
     */
    function initALLDatePickers(laydate) {
        $.each(datePickerSelectorArray, function(index, keyword) {
            $.each(['.start', '.end'], function(i, suffix) {
                var name = keyword + suffix;
                $('input[name="' + name + '"]').each(function() {
                    renderDatePicker.call(laydate, this, name);
                });
            });
        });

        $('.date-picker-item:not(.inline-block) input').prop('disabled', true);
    }

    /**
     * 初始化跟单信息
     */
    var initCurrentTrackInfo = function(data) {
        let workIdArr = [];
        data.forEach(e => {
            workIdArr.push(e.workId)
        })
        let params = {
            body: {
                workIdList: workIdArr
            }
        }
        if (workIdArr.length == 0) {
            return
        }
        $.ajax({
            url: ZMN_CONFIG.BASE_URL.GATEWAY_API_BASE + WORK_TRACK_CURRENT_LOG_LIST_URL,
            type: 'POST',
            contentType: "application/json",
            dataType: "json",
            data: JSON.stringify(params),
            success: function(response) {
                if (response.status != 200) {
                    return
                }
                let trackList = response.data;
                let groups = {};
                trackList.forEach(c => {
                    let value = c['workId'];
                    groups[value] = groups[value] || [];
                    groups[value].push(c);
                });
                for (let groupsKey in groups) {
                    var group = groups[groupsKey];
                    if (group.length > 0) {
                        $("#btn-track-info" + groupsKey).html(group[0]['content']);
                    }
                }
            },
            error: function() {
                layer.msg('网络错误，请重试');
            }
        })
    }

    /**
     * 初始化备注跟单提示框
     */
    var initTrackInfoHoverTips = (function() {
        function fetchWorkTrackInfoList(params, cb) {
            $.ajax({
                url: WORK_TRACK_LOG_URL,
                type: 'GET',
                data: params,
                success: function(response) {
                    if (response.status === 200) {
                        cb(response.data);
                    } else {
                        layer.msg(response.message);
                    }
                },
                error: function() {
                    layer.msg('网络错误，请重试');
                }
            })
        }

        function createWorkTrackHtml(data) {
            if (!data.length) {
                return '暂无跟单记录';
            }

            function createTrackContentHtml(data) {
                var htmlStr = '';

                data.forEach((item) => {
                    htmlStr += '<tr>' +
                        '      <td>' + item.createTime + '</td>' +
                        '      <td>' + item.typeName + '</td>' +
                        '      <td>' + item.content + '</td>' +
                        '      <td>' + item.beforeStatusName + '-->' + item.afterStatusName + '</td>' +
                        '      <td>' + item.operator + '</td>' +
                        '    </tr>';
                });

                return htmlStr;
            }

            var htmlStr = '<table lay-filter="track">' +
                '  <thead>' +
                '    <tr>' +
                '      <th lay-data="{field:\'createTime\', width:100}">操作时间</th>' +
                '      <th lay-data="{field:\'typeName\', width:100}">操作</th>' +
                '      <th lay-data="{field:\'content\'}">操作内容</th>' +
                '      <th lay-data="{field:\'beforeStatusName-->afterStatusName\', width:80}">状态变更</th>' +
                '      <th lay-data="{field:\'operator\', width:80}">操作员</th>' +
                '    </tr> ' +
                '  </thead>' +
                '  <tbody>' +
                createTrackContentHtml(data) +
                '  </tbody>' +
                '</table>';
            return htmlStr;
        }

        function createWorkTrackInfoHtml(data) {
            var remarkData = [];
            var trackData = [];

            if (!data.length) {
                return '暂无跟单记录';
            }

            data.forEach(function(item) {
                if (item.type === 200) {
                    trackData.push(item);
                } else {
                    remarkData.push(item);
                }
            });

            return '<div class="layui-collapse">' +
                '  <div class="layui-colla-item">' +
                '    <h2 class="layui-colla-title">跟单</h2>' +
                '    <div class="layui-colla-content layui-show">' + createWorkTrackHtml(trackData) + '</div>' +
                '  </div>' +
                '</div>';
        }

        function renderWorkTrackInfoList(params, instance) {
            fetchWorkTrackInfoList(params, function(data) {
                var htmlStr = createWorkTrackInfoHtml(data);

                instance.content(htmlStr);

                table.init('remark', {
                    limit: 1000
                });

                table.init('track', {
                    limit: 1000
                });
            })
        }

        return function(btn) {
            var $triggers = btn ? $(btn) : $('.btn-track-info');
            $triggers.tooltipster({
                content: 'Loading...',
                side: 'bottom',
                theme: 'tooltipster-layui',
                maxWidth: 930,
                interactive: true,
                contentAsHTML: true,
                updateAnimation: 'null',
                functionBefore: function(instance, helper) {
                    var $origin = $(helper.origin);
                    var workId = $origin.data('id');
                    renderWorkTrackInfoList({
                        id: workId
                    }, instance);
                }
            });
        }
    })();

    /**
     * 初始化备注跟单提示框
     */
    var initRemarkHoverTips = (function() {
        function fetchWorkTrackRemarkList(params, cb) {
            $.ajax({
                url: WORK_TRACK_REMARK_URL,
                type: 'GET',
                data: params,
                success: function(response) {
                    if (response.status === 200) {
                        cb(response.data);
                    } else {
                        layer.msg(response.message);
                    }
                },
                error: function() {
                    layer.msg('网络错误，请重试');
                }
            })
        }

        function createWorkRemarkHtml(data) {
            if (!data.length) {
                return '暂无更多备注记录';
            }

            function createRemarkContentHtml(data) {
                var htmlStr = '';

                data.forEach((item) => {
                    htmlStr += '<tr>' +
                        '      <td>' + item.createTime + '</td>' +
                        '      <td>' + item.operatorTypeName + '</td>' +
                        '      <td>' + item.operator + '</td>' +
                        '      <td>' + item.typeName + '</td>' +
                        '      <td>' + item.content + '</td>' +
                        '    </tr>';
                });

                return htmlStr;
            }

            var htmlStr = '<table lay-filter="remark">' +
                '  <thead>' +
                '    <tr>' +
                '      <th lay-data="{field:\'createTime\', width:200}">操作时间</th>' +
                '      <th lay-data="{field:\'operatorTypeName\', width:100}">操作员角色</th>' +
                '      <th lay-data="{field:\'operator\', width:100}">操作员名称</th>' +
                '      <th lay-data="{field:\'typeName\', width:100}">备注类型</th>' +
                '      <th lay-data="{field:\'content\', width:300}">备注内容</th>' +
                '    </tr> ' +
                '  </thead>' +
                '  <tbody>' +
                createRemarkContentHtml(data) +
                '  </tbody>' +
                '</table>';

            return htmlStr;
        }

        function createWorkTrackRemarkHtml(data) {
            var remarkData = [];
            var trackData = [];

            if (!data.length) {
                return '暂无更多备注记录';
            }

            data.forEach(function(item) {
                if (item.type === 200) {
                    trackData.push(item);
                } else {
                    remarkData.push(item);
                }
            });

            return '<div class="layui-collapse">' +
                '  <div class="layui-colla-item">' +
                '    <h2 class="layui-colla-title">备注</h2>' +
                '    <div class="layui-colla-content layui-show">' + createWorkRemarkHtml(remarkData) + '</div>' +
                '  </div>' +
                '</div>';
        }

        function renderWorkTrackRemarkList(params, instance) {
            fetchWorkTrackRemarkList(params, function(data) {
                var htmlStr = createWorkTrackRemarkHtml(data);

                instance.content(htmlStr);

                table.init('remark', {
                    limit: 1000
                });

                table.init('track', {
                    limit: 1000
                });
            })
        }

        return function(btn) {
            var $triggers = btn ? $(btn) : $('.btn-remark');

            $triggers.tooltipster({
                content: 'Loading...',
                side: 'bottom',
                theme: 'tooltipster-layui',
                maxWidth: 930,
                interactive: true,
                contentAsHTML: true,
                updateAnimation: 'null',
                functionBefore: function(instance, helper) {
                    var $origin = $(helper.origin);
                    var workId = $origin.data('id');

                    renderWorkTrackRemarkList({
                        id: workId
                    }, instance);
                }
            });
        }
    })();

    /**
     * 初始化警示提示框
     */
    var initWarningHoverTips = function(btn) {
        var $triggers = btn ? $(btn) : $('.warning').closest('td');

        $triggers.tooltipster({
            content: 'Loading...',
            side: 'right',
            theme: 'tooltipster-layui',
            maxWidth: 930,
            interactive: true,
            contentAsHTML: true,
            updateAnimation: 'null',
            functionBefore: function(instance, helper) {
                var $origin = $(helper.origin);
                var contentHtml = $origin.find('.warning-content').html();

                instance.content(contentHtml);
            }
        });
    };

    /**
     * 初始化工单子状态提示框
     */
    var initVisitStatusHoverTips = function(btn) {
        var $triggers = btn ? $(btn) : $('.order-status').closest('td');

        if ($triggers) {
            $triggers.tooltipster({
                content: 'Loading...',
                side: 'bottom',
                theme: 'tooltipster-layui',
                maxWidth: 930,
                interactive: true,
                contentAsHTML: true,
                updateAnimation: 'null',
                functionBefore: function(instance, helper) {
                    var $origin = $(helper.origin);
                    var contentHtml = $origin.find('.visit-content').html();

                    instance.content(contentHtml);
                }
            });
        }
    };

    /**
     * 初始化地址提示框
     */
    function initAddressHoverTips(btn) {
        var $triggers = btn ? $(btn) : $('.btn-address');

        $triggers.tooltipster({
            content: 'Loading...',
            side: 'bottom',
            theme: 'tooltipster-layui',
            interactive: true,
            updateAnimation: 'null',
            functionBefore: function(instance, helper) {
                var $origin = $(helper.origin);
                instance.content($origin.data('address'));
            }
        });
    }

    /**
     * 初始化公司名称提示框
     */
    function initCompanyInfoHoverTips(btn) {
        var $triggers = btn ? $(btn) : $('.btn-company');

        $triggers.tooltipster({
            content: 'Loading...',
            side: 'bottom',
            theme: 'tooltipster-layui',
            interactive: true,
            updateAnimation: 'null',
            functionBefore: function(instance, helper) {
                var $origin = $(helper.origin);
                instance.content($origin.data('company'));
            }
        });
    }

    /**
     * 渲染表格
     * @param {object} params 查询参数
     * @param {array} data 表格数据
     * @returns {object}
     */
    var renderTable = (function($) {
        var tableCols = table.getConfig('zmn-work-table').cols;
        if (typeof(autoSort) != 'undefined' && autoSort == false) {
            var cols = tableCols[0];
            cols.forEach(function(item, index) {
                cols[index].sort = false;
            });
        }

        var defaultConfig = $.extend({
            id: 'zmn-work-table',
            elem: '#zmn-work-table',
            method: 'POST',
            contentType: 'application/json;charset=utf-8',
            limit: 100,
            limits: [100],
            data: null,
            cols: tableCols,
            parseData: function(res) {
                var count = res.data ? res.data.count : 0;
                $('.layui-this').find('.count').text('（共 ' + count + ' 条）');

                return {
                    "code": res.status, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.data ? (res.data.count > 10000 ? 10000 : res.data.count) : 0, //解析数据长度
                    "data": res.data ? res.data.data : [] //解析数据列表
                };
            },
            done: function(res, curr, count) {
                operationUtils.initOpPanel({}, function($elem) {
                    var orderId = $elem.data('order-id');
                    var workId = $elem.data('work-id');

                    var params = {
                        orderId: orderId,
                        workId: workId,
                    };

                    return params;
                });

                initCurrentTrackInfo(res.data);

                initWarningHoverTips();

                initAddressHoverTips();

                initRemarkHoverTips();

                initTrackInfoHoverTips();

                initCompanyInfoHoverTips();

                initVisitStatusHoverTips();
            }
        }, tableConfig.config);

        return function(params, data) {
            var where = { where: $.extend({}, tableConfig.orderObj, params) };
            var config = $.extend({}, defaultConfig, where, { data: data || null });

            return zmnTable.init({
                config: config,
                filter: 'zmn-work-table',

                event: function() {
                    table.on('tool(zmn-work-table)', function(rowObj) {
                        if (rowObj.event === 'operate') {
                            updateRowData(rowObj);
                        }
                    });

                    table.on('rowDouble(zmn-work-table)', function(rowObj) {
                        var url = zmnUtils.serializeURL(OMS_BASE_URL + '/work/modify/detail.action', {
                            workId: rowObj.data.workId,
                            orderId: rowObj.data.orderId,
                            moduleId: tableConfig.moduleId,
                            operateId: 103
                        });

                        window.currentWork = rowObj.data;

                        operationUtils.openDialog({
                            title: '详情',
                            content: url,
                            end: function() {
                                updateRowDataByWorkId();
                            }
                        });
                    });

                }
            });
        }

    })($);

    /**
     * 搜索框搜索方法
     * @param {object} params 查询参数
     */
    function searchForTable(params, data) {
        tableInstance = renderTable(params, data);
    }

    /**
     * 获取工单信息
     * @param {object} params 查询参数
     * @param {function} cb 回调函数
     */
    function fetchWorkInfo(params) {
        return $http.$get(tableConfig.rowURL, params);
    }

    /**
     * 根据工单 id 更新行数据
     * @param workId
     */
    function updateRowDataByWorkId() {
        var currentWork = window.currentWork;
        if (currentWork && currentWork.workId) {
            $('.btn-operate[data-work-id="' + currentWork.workId + '"]').first().trigger('click');
        }
    }

    window.updateRowDataByWorkId = updateRowDataByWorkId;

    /**
     * 更新表格单行数据
     * @param rowObj 表格数据行对象
     * @param data 行数据
     */
    function updateRowData(rowObj, data) {
        if (!rowObj) {
            return;
        }

        if (data) {
            rowObj.update(data);
            return;
        }

        fetchWorkInfo({ id: rowObj.data.workId }).done(function(info) {
            rowObj.update(info);

            var $tr = $(rowObj.tr);

            $tr.css('backgroundColor', 'RGBA(0, 139, 125, .2)').siblings().css('backgroundColor', '');

            initWarningHoverTips($tr.find('.warning').closest('td'));
            initAddressHoverTips($tr.find('.btn-address'));
            initRemarkHoverTips($tr.find('.btn-remark'));
            initTrackInfoHoverTips($tr.find('.btn-track-info'));
        });
    }

    /**
     * 标准化搜索参数
     * @param {object} field 参数
     */
    function normalizeSearchParams(field, formElem) {
        var params = {};

        // 整理时间
        datePickerSelectorArray.forEach(function(keyword) {
            var startSelector = keyword + '.start';
            var endSelector = keyword + '.end';

            var $startInput = $(formElem).find('input[name="' + startSelector + '"]');
            var $endInput = $(formElem).find('input[name="' + endSelector + '"]');

            if (!$startInput.prop('disabled') || !$endInput.prop('disabled')) {
                var startTime = field[startSelector];
                var endTime = field[endSelector];

                if (startTime || endTime) {
                    // startTime = startTime ? startTime + ' ' + '00:00:00' : '';
                    // endTime = endTime ? endTime + ' ' + '23:59:59' : '';

                    params[keyword] = startTime + ',' + endTime;
                }
            }

            field[startSelector] = '';
            field[endSelector] = '';
        });

        // 整理工单号
        if (field['code'] && field['code'].length) {
            if (field['code'].length > 19) {
                field['code'] = field['code'].substring(0, 19);
            }

            if (field['code'].length === 6) {
                params['codeEnd6'] = field['code'];
                field['code'] = '';
            }
        }

        // 整理源单号
        if (field['originalId'] && field['originalId'].length) {
            if (field['originalId'].length > 19) {
                field['originalId'] = field['originalId'].substring(0, 19);
            }
        }

        // 整理操作类型、操作员
        if (field['operate_operateType'] || field['operate_operatorId']) {
            params['operate'] = {
                operateType: field['operate_operateType'] || null,
                operatorId: field['operate_operatorId'] || null
            };

            field['operate_operateType'] = null;
            field['operate_operatorId'] = null;
        }

        // 整理加单工程师
        if (field['recommenderId']) {
            params['recommenderType'] = 3;
        }

        // 整理优惠
        if (field['discount.discountCateg'] || field['discount.discountType']) {
            params['discount'] = {
                discountCateg: field['discount.discountCateg'],
                discountType: field['discount.discountType']
            };

            field['discount.discountCateg'] = null;
            field['discount.discountType'] = null;
        }


        // 拷贝非空字段
        Object.keys(field).filter((key) => {
            if (field[key]) {
                if (multipleSelectNameArray.indexOf(key) !== -1) {
                    params[key] = field[key].split(',');
                } else {
                    params[key] = field[key];
                }
            }
        });

        // 订单收入
        if (params['totalAmountRangeMin'] || params['totalAmountRangeMax']) {
            let totalAmountRangeMin = /^-?\d+$/.test(params['totalAmountRangeMin']) ? params['totalAmountRangeMin'] * 100 : '';
            let totalAmountRangeMax = /^-?\d+$/.test(params['totalAmountRangeMax']) ? params['totalAmountRangeMax'] * 100 : '';
            params['totalAmountRange'] = totalAmountRangeMin + ',' + totalAmountRangeMax;
            delete params['totalAmountRangeMin'];
            delete params['totalAmountRangeMax'];
        }

        // 整理加单工程师
        if (field['sourceChannelIdList']) {
            var sourceChannelIdList = field['sourceChannelIdList'];
            params['sourceChannelIdList'].concat(sourceChannelIdList);
        }
        // 拼接渠道
        var channelIdList = params['channelIdList'] || [];
        var channelIdListOfInput = (params['channelIdListOfInput'] || '')
            .replace(/\s/g, '')
            .replace(/\，/g, ',')
            .replace(/^\,/, '')
            .replace(/\,$/, '')
            .split(',')
            .filter(function(item) {
                return !!item;
            });
        channelIdList = channelIdList.concat(channelIdListOfInput);
        if (channelIdList.length) {
            params['channelIdList'] = channelIdList;
        } else {
            delete params['channelIdList'];
        }
        delete params['channelIdListOfInput'];

        // 拼接一级渠道
        var channelOneIdList = params['channelTwoIdList'] || [];
        if (channelOneIdList.length) {
            params['channelTwoIdList'] = channelOneIdList;
        } else {
            delete params['channelTwoIdList'];
        }

        // tabType
        if (!field['tabType']) {
            var $currentTab = $('.tab-work-list .layui-tab-title .layui-this');
            if ($currentTab) {
                params['tabType'] = $currentTab.data('type');
            }
        }

        // 前后台产品处理
        if ($('#productType').val() == 1) {
            // 选择前台产品，删除后台产品相关
            delete params['categOneIdList'];
            delete params['categTwoIdList'];
            delete params['productIdList'];
        } else {
            // 选择后台产品，删除前台产品相关
            delete params['showCategOneIdList'];
            delete params['showCategTwoIdList'];
            delete params['showProductIdList'];
        }

        return params;
    }

    /**
     * 初始化页面事件
     */
    function initEvent() {
        $('body').on('blur', 'input', function() {
            let $this = $(this);
            $this.val($this.val().replace(/(^\s*)|(\s*$)/g, ''));
        });
        // 号码处理
        $('body').on('blur', '.concat-phone', function() {
            let $concatPhone = $(this);
            if ($concatPhone.val() != $concatPhone.data('showPhone')) {
                let $cryptoPhone = $concatPhone.next();
                if ($cryptoPhone.length > 0 && $cryptoPhone.hasClass('crypto-phone')) {
                    $concatPhone.data('showPhone', '');
                    $cryptoPhone.val('');
                }
            }
        });
        $('body').on('paste', '.concat-phone', function() {
            // 粘贴处理
            let $concatPhone = $(this);
            let $cryptoPhone = $concatPhone.next();
            if ($cryptoPhone.length > 0 && $cryptoPhone.hasClass('crypto-phone')) {
                setTimeout(function() {
                    let concatPhone = $concatPhone.val();
                    if (concatPhone && concatPhone.match(/\{\s*\"show\"\s*\:\s*\"(?<show>.+)\"\s*\,\s*\"ciphertext\"\s*\:\s*\"(?<ciphertext>.+)\"\s*\}/)) {
                        let data = JSON.parse(concatPhone);
                        $concatPhone.val(data.show);
                        $concatPhone.data('showPhone', data.show);
                        $cryptoPhone.val(data.ciphertext);
                    } else if (concatPhone.indexOf('**') > 0) {
                        $concatPhone.val('');
                        $concatPhone.data('showPhone', '');
                        $cryptoPhone.val('');
                    }
                }, 20);
            }
        });

        element.on('tab(workListTabBrief)', function(obj) {
            var $this = $(this);
            var type = +$this.data('type');
            var $tabContent = $('#tab-content');

            // 新版处理
            if ($tabContent.data('version') === 2) {
                var queryView = $this.data('view');

                if ($tabContent.data('view') == queryView) {
                    $tabContent.find('.search-form').removeClass('layui-hide').addClass('layui-show');
                    return;
                } else {
                    $tabContent.find('.search-form').removeClass('layui-show').addClass('layui-hide');
                }

                if (queryView) {
                    window.location.href = window.location.pathname + '?queryView=' + queryView;
                    return;
                }

                // 不自动查询
                if ($this.data('autoquery') === 1) {
                    return;
                }

                if (type === 0 || type === -1) {
                    return;
                }

                renderTable({ tabType: type });
                return;
            }

            var type = +$this.data('type');
            var redirectURL = $this.data('url');

            if (redirectURL) {
                window.location.href = redirectURL;
                return;
            }

            // 不自动查询
            if ($this.data('autoquery') === 1) {
                return;
            }

            if (type === -1) {
                return;
            }

            renderTable({ tabType: type });
        });

        // 监听重置按钮点击
        form.on('submit(submit-reset)', function(obj) {
            setTimeout(function() {
                clearZmnSelectedValue('companyIdOrGridCompanyIdList');
                clearZmnSelectedValue('manageCompanyIdOrGridManageCompanyId');
                clearZmnSelectedValue('manageCompanyIdOrGridManageCompanyIdList');
                clearZmnSelectedValue('companyIdList');
                clearZmnSelectedValue('manageCompanyId');
                clearZmnSelectedValue('manageCompanyIdList');
                clearZmnSelectedValue('gridCompanyIdList');
                clearZmnSelectedValue('gridManageCompanyId');
                clearZmnSelectedValue('gridManageCompanyIdList');
                clearZmnSelectedValue('provinceIdList');
                clearZmnSelectedValue('cityIdList');
                clearZmnSelectedValue('countyIdList');
                clearZmnSelectedValue('servCategId');
                clearZmnSelectedValue('categOneIdList');
                clearZmnSelectedValue('categTwoIdList');
                zmnOmsSelect.clearSelectedData('productIdList');
                clearZmnSelectedValue('showCategOneIdList');
                clearZmnSelectedValue('showCategTwoIdList');
                zmnOmsSelect.clearSelectedData('showProductIdList');
                clearZmnSelectedValue('servProductGroupIdList');
                clearZmnSelectedValue('masterId');
                clearZmnSelectedValue('multiMasterId');
                clearZmnSelectedValue('cancelLiableMasterId');
                clearZmnSelectedValue('recommenderId');
                clearZmnSelectedValue('masterSupervisorId');
                clearZmnSelectedValue('channelTwoIdList');
                clearZmnSelectedValue('channelIdList');
                clearZmnSelectedValue('sourceChannelTwoIdList');
                clearZmnSelectedValue('sourceChannelIdList');
                zmnOmsSelect.clearSelectedData('gridIdList');
                zmnOmsSelect.clearSelectedData('workResultStatus');
                zmnOmsSelect.clearSelectedData('workStatusList');
                zmnOmsSelect.clearSelectedData('workTypeList');
                zmnOmsSelect.clearSelectedData('visitType');
                zmnOmsSelect.clearSelectedData('visitStatus');
                zmnOmsSelect.clearSelectedData('orderPostStatusList');
                zmnOmsSelect.clearSelectedData('multiMaster');
                zmnOmsSelect.clearSelectedData('duplicate');
                zmnOmsSelect.clearSelectedData('operate_operateType');
                zmnOmsSelect.clearSelectedData('tagIdList');
                zmnOmsSelect.clearSelectedData('userLevel');
                zmnOmsSelect.clearSelectedData('brandId');
                zmnOmsSelect.clearSelectedData('payStatusList');
                zmnOmsSelect.clearSelectedData('refundWorkReviewStatusList');
                zmnOmsSelect.clearSelectedData('compensateWorkReviewStatusList');
                zmnOmsSelect.clearSelectedData('partReimburseStatus');
                zmnOmsSelect.clearSelectedData('partakeQuotationTypeList');
                zmnOmsSelect.clearSelectedData('quotationType');
                zmnOmsSelect.clearSelectedData('cancelerTypeList');
                zmnOmsSelect.clearSelectedData('failMapIdList');
                zmnOmsSelect.clearSelectedData('workCancelResultStatus');
                zmnOmsSelect.clearSelectedData('workCancelStatusList');
                zmnOmsSelect.clearSelectedData('refundType');
                clearZmnSelectedValue('operate_operatorId');
                clearZmnSelectedValue('cancelerId');

                // $('input:checkbox').each(function (idx, obj) {
                //     console.log(obj)
                //     let $this = $(this);
                //     if(idx == 0){
                //         if(obj.checked != true){
                //             $this.next('.layui-form-checkbox').find('.layui-icon').trigger('click');
                //         }
                //     } else {
                //         if(obj.checked == true){
                //             $this.next('.layui-form-checkbox').find('.layui-icon').trigger('click');
                //         }
                //     }
                // })
                //form.render();
            }, 100);

            return true;
        });

        // 监听时间选择器控制选择框点击事件
        form.on('checkbox(datepicker)', function(data) {
            const $boxThat = $(data.elem);
            var boxTitle = $boxThat.attr('title');
            var dpIndex = -1;
            $boxThat.parent().find('input:checkbox').each(function(idx, obj) {
                if ($(obj).attr('title') == boxTitle) {
                    dpIndex = idx;
                }
            })
            var $dataPicker = $boxThat.closest('form')
                .find('.date-picker-item').eq(dpIndex);
            if (data.elem.checked) {
                $dataPicker.addClass('inline-block').find('input').attr('disabled', false);
            } else {
                $dataPicker.removeClass('inline-block').find('input').prop('disabled', true);
            }

            form.render();
        });

        // 监听查询表单提交事件
        form.on('submit(submit-search)', function(obj) {
            var params = normalizeSearchParams(obj.field, obj.form);
            let pageUrl = window.location.href;
            var filter_name = ''
            Object.keys(params).forEach((item, index) => {
                var fifname = $('[name^="' + item + '"]').parents('.layui-input-inline').eq($('[name^="' + item + '"]').parents('.layui-input-inline').length - 1).prev().text().split('：')[0]

                if (index != Object.keys(params).length - 1) {
                    filter_name = filter_name + fifname + '|'
                } else {
                    filter_name = filter_name + fifname
                }

            })


            try {
                if (filter_name.substring(filter_name.length - 1) == '|') {
                    filter_name = filter_name.substring(0, filter_name.length - 1)
                }
                console.log(filter_name)
                var data = {
                    employee_name: loginStaff.realName, // 内部员工姓名,
                    employee_id: loginStaff.staffId,
                    department_name: loginStaff.deptName, // 员工部门名称
                    department_id: loginStaff.deptId,
                    menu: path_name, //菜单目录路径名称
                    filter_name: filter_name,
                    tab_name: tabName || ''

                }
                webTrackingUtil('SYS_ADMIN_QUERY', pageUrl, 'click', 'SYS_ADMIN_QUERY_CLICK', data)
            } catch (error) {
                console.log(error)
            }






            if (!Object.keys(params).length) {
                layer.msg('请至少选择一个查询条件');
                return false;
            }

            // 默认字段 tabType: 0
            if ((tableConfig.paramsNotEmpty == undefined || tableConfig.paramsNotEmpty == true) && Object.keys(params).length <= 1) {
                layer.msg('请至少选择一个查询条件');
                return false;
            }

            var $tabContent = $('#tab-content');
            if ($tabContent.data('version') === 2) {
                // 查询后隐藏查询条件
                // var $form = $tabContent.find('.search-form');
                // if ($form) {
                //     $form.removeClass('layui-show').addClass('layui-hide');
                // }
            } else {
                // 修改查询框状态
                // var $currentTab = $('.tab-work-list .layui-tab-title .layui-this');
                // $tabContent.find('.layui-tab-item').removeClass('layui-show');
            }

            searchForTable(params);
            return false;
        });

        // 监听查询表单导出事件
        form.on('submit(submit-export)', function(obj) {
            $("#submit-export").addClass("layui-btn-disabled").attr("disabled", true);
            setTimeout(function() {
                $("#submit-export").removeClass("layui-btn-disabled").removeAttr("disabled");
            }, 10000);
            var params = normalizeSearchParams(obj.field, obj.form);

            if (!Object.keys(params).length) {
                layer.msg('请至少选择一个查询条件');
                $("#submit-export").removeClass("layui-btn-disabled").removeAttr("disabled");
                return false;
            }

            // 默认字段 tabType: 0
            if ((tableConfig.paramsNotEmpty == undefined || tableConfig.paramsNotEmpty == true) && Object.keys(params).length <= 1) {
                layer.msg('请至少选择一个查询条件');
                return false;
            }

            if (!tableConfig.exportURL) {
                layer.msg('请添加导出 URL');
                $("#submit-export").removeClass("layui-btn-disabled").removeAttr("disabled");
                return false;
            }

            layer.tips('至多导出 5000 条', obj.elem, {
                success: function() {
                    if (tableConfig.exportAsync && tableConfig.exportAsync == true) {
                        $.ajax({
                            type: 'POST',
                            url: tableConfig.exportURL,
                            contentType: 'application/json; charset=utf-8',
                            data: JSON.stringify(params),
                            async: false,
                            dataType: 'json',
                            success: function(res) {
                                if (res.status == 200) {
                                    top.layui.index.openTabsPage(config.elephantHost + '/tapi/export/list.action', "导出文件管理");
                                } else {
                                    layer.msg(res.message, { icon: 2 });
                                }
                            },
                            error: function(res) {
                                layer.msg('操作发生异常，请重试', { icon: 5 });
                            }
                        });
                    } else {
                        setTimeout(function() {
                            layui.zmnUtils.exportFile(tableConfig.exportURL, params);
                        }, 300);
                    }
                }
            });

            return false;
        });

        // 预约失败
        form.on('select(isDutyFail)', function(obj) {
            $('#dutyFailReasonCode').val('');
            if (obj.value == 2) {
                $('#dutyFailReasonCode').removeAttr('disabled');
            } else {
                $('#dutyFailReasonCode').attr('disabled', 'disabled');
            }
            form.render('select');
        });
        // 挂起
        form.on('select(isDutySuspend)', function(obj) {
            $('#dutySuspendReasonCode').val('');
            if (obj.value == 2) {
                $('#dutySuspendReasonCode').removeAttr('disabled');
            } else {
                $('#dutySuspendReasonCode').attr('disabled', 'disabled');
            }
            form.render('select');
        });

        // 前后台产品选择
        form.on('select(select-productType)', function(obj) {
            let $el = $('.product-select').parents('.layui-inline');
            $el.find('.product-select').toggle();
            $el.find('.product-select:hidden').each((inx, item) => {
                let $that = $(item);
                $that.find('.layui-input-inline').find(':first').each(function() {
                    let id = $(this).attr("id");
                    console.log(id);
                    if (id == 'showProductIdList' || id == 'productIdList') {
                        zmnOmsSelect.reloadXmSelect(id);
                    } else {
                        zmnSelect.reloadXmSelect(id);
                    }
                });
            });
        });

        // 更多
        $('#more-up').on('click', function(obj) {
            $('.more-up').hide();
            //$('.area-item').addClass('input-large');
            $('.more-down').show();
            $('.query-more-item').show();
        });
        $('#more-down').on('click', function(obj) {
            //$('.area-item').removeClass('input-large');
            $('.more-down').hide();
            $('.query-more-item').hide();
            $('.more-up').show();
        });
    }

    function checkExistId(id) {
        let $id = $('#' + id);
        return $id.length > 0;
    }

    function clearZmnSelectedValue(selectId) {
        try {
            let select = zmnSelect.getXmSelect(selectId);
            if (select && zmnUtil.isObject(select) && zmnUtil.isFunction(select.setValue)) {
                select.setValue([]);
            }
        } catch (e) {}
    }

    /**
     * 初始化页面所有下拉框
     */
    function initAllSelect() {

        // 公司&服务商 单选
        if (checkExistId('companyIdOrGridCompanyIdList')) {

            selectSearch.subCompanyAndSpCompanySearchInit(
                {
                    plat: plat,
                    isRadio: true,
                    subCompanyId: "companyIdOrGridCompanyIdList",
                    manageCompanyId: 'manageCompanyIdOrGridManageCompanyId'
                },
                (values) => json.vo.companyIdOrGirdCompanyIdList = values,
                (values) => json.vo.spCompanyOrGridSpCompanyIdIdList = values,
            )
        }

        // 公司&执行服务商 单选
        if (checkExistId('companyIdList')) {

                selectSearch.subCompanyAndSpCompanySearchInit(
                    {
                        plat: plat,
                        isRadio: true,
                        subCompanyId: "companyIdList",
                        manageCompanyId: 'manageCompanyId'
                    },
                    (values) => {
                        json.vo.companyIdList = values;
                        json.vo.companyId = zmnUtil.isArray(values) && values.length > 0 ? values[0] : null;
                    },
                    (values) => {
                        json.vo.spCompanyIdList = values;
                        json.vo.spCompanyId = zmnUtil.isArray(values) && values.length > 0 ? values[0] : null;
                    },
                )
        }

        // 行政服务商 单选
        if (checkExistId('gridCompanyIdList')) {

            selectSearch.subCompanyAndSpCompanySearchInit(
                {
                    plat: plat,
                    isRadio: true,
                    subCompanyId: "gridCompanyIdList",
                    manageCompanyId: 'gridManageCompanyId'
                },
                (values) => {
                    json.vo.gridCompanyIdList = values;
                    json.vo.gridCompanyId = zmnUtil.isArray(values) && values.length > 0 ? values[0] : null;
                },
                (values) => {
                    json.vo.gridSpCompanyIdList = values;
                    json.vo.gridSpCompanyId = zmnUtil.isArray(values) && values.length > 0 ? values[0] : null;
                }
            )
        }

        // 公司&服务商 多选
        if (checkExistId('companyIdOrGridCompanyIdList')) {

            selectSearch.subCompanyAndSpCompanySearchInit(
                {
                    plat: plat,
                    subCompanyId: "companyIdOrGridCompanyIdList",
                    manageCompanyId: 'manageCompanyIdOrGridManageCompanyIdList'
                },
                (values) => json.vo.companyIdOrGirdCompanyIdList = values,
                (values) => json.vo.spCompanyOrGridSpCompanyIdIdList = values,
            )

        }

        // 公司&执行服务商 多选
        if (checkExistId('companyIdList')) {

            selectSearch.subCompanyAndSpCompanySearchInit(
                {
                    plat: plat,
                    subCompanyId: "companyIdList",
                    manageCompanyId: 'manageCompanyIdList'
                },
                (values) => {
                    json.vo.companyIdList = values;
                    json.vo.companyId = zmnUtil.isArray(values) && values.length > 0 ? values[0] : null;
                },
                (values) => {
                    json.vo.spCompanyIdList = values;
                    json.vo.spCompanyId = zmnUtil.isArray(values) && values.length > 0 ? values[0] : null;
                },
            )
        }

        // 行政服务商 多选
        if (checkExistId('gridCompanyIdList')) {
            selectSearch.subCompanyAndSpCompanySearchInit(
                {
                    plat: plat,
                    subCompanyId: "gridCompanyIdList",
                    manageCompanyId: 'gridManageCompanyIdList'
                },
                (values) => {
                    json.vo.gridCompanyIdList = values;
                    json.vo.gridCompanyId = zmnUtil.isArray(values) && values.length > 0 ? values[0] : null;
                },
                (values) => {
                    json.vo.gridSpCompanyIdList = values;
                    json.vo.gridSpCompanyId = zmnUtil.isArray(values) && values.length > 0 ? values[0] : null;
                }
            )
        }

        // 省份、城市、区域
        if (checkExistId('provinceIdList')) {
            zmnSelect.selectlAreas({
                provinceSelectId: 'provinceIdList',
                citySelectId: 'cityIdList',
                countySelectId: checkExistId('countyIdList') ? 'countyIdList' : null,
            }, {
                provinceSelectId: {
                    isRadio: false,
                    events: {
                        changed: function(values) {
                            if (values.length == 0) {
                                // 默认加载 城市
                                zmnSelect.reloadXmSelect('cityIdList', {
                                    tips: "-选择城市-",
                                    isReload: true
                                });
                            }
                        }
                    }
                },
                citySelectId: {
                    isRadio: false,
                    events: {
                        changed: function(values) {
                            // 查询网格列表
                            zmnOmsSelect.reloadXmSelect('gridIdList');
                        }
                    }
                },
                countySelectId: {
                    isRadio: false
                },
            });

            // 默认加载 城市
            zmnSelect.reloadXmSelect('cityIdList', {
                tips: "-选择城市-",
                isReload: true
            });
        } else if (checkExistId('cityIdList')) {
            zmnSelect.selectCity('cityIdList', {
                tips: "-选择城市-",
                isReload: true
            });
        }

        // 服务分类
        if (checkExistId('servCategId')) {
            zmnSelect.selectServCategory('servCategId', {
                tips: "-选择服务分类-",
                isReload: true,
                isRadio: true,
                events: {
                    /*changed(values) {
                        json.vo.servCategId = zmnUtil.isArray(values) && values.length > 0 ? values[0] : null;

                        if (checkExistId('showProductIdList')) {
                            zmnOmsSelect.reloadXmSelect('showProductIdList', {
                                remote: {
                                    events: {
                                        extendParams: function() {
                                            let data = {
                                                servCategoryId: json.vo.servCategId,
                                                categIds: json.vo.categTwoIdList,
                                            }
                                            return { body: data };
                                        }
                                    }
                                }
                            });
                        }

                        if (checkExistId('productIdList')) {
                            zmnOmsSelect.reloadXmSelect('productIdList', {
                                remote: {
                                    events: {
                                        extendParams: function() {
                                            let data = {
                                                servCategoryId: json.vo.servCategId,
                                                categIds: json.vo.categTwoIdList,
                                            }
                                            return { body: data };
                                        }
                                    }
                                }
                            });
                        }
                    }*/
                }
            });
        }

        // 业务分类、产品分组
        if (checkExistId('bizType') && checkExistId('servProductGroupIdList')) {
            zmnSelect.selectlServBizTypeGroup({
                bizTypeSelectId: 'bizType',
                prodGroupSelectId: 'servProductGroupIdList',
            }, {
                bizTypeSelectId: {
                    selectedValues: json.vo.bizType == null ? null : json.vo.bizType,
                    isRadio: true,
                    events: {
                        changed(values) {
                            json.vo.bizType = zmnUtil.isArray(values) && values.length > 0 ? values[0] : null;
                        }
                    }
                },
                prodGroupSelectId: {
                    events: {
                        changed(values) {}
                    }
                },
            });
        } else if (checkExistId('bizType')) {
            zmnSelect.selectBizType('bizType', {
                selectedValues: json.vo.bizType == null ? null : json.vo.bizType,
                isRadio: true,
            });
        }

        // 前台一二级分类
        if (checkExistId('showCategOneIdList')) {
            zmnSelect.selectlEcProdCategories({
                ecCategOneSelectId: 'showCategOneIdList',
                ecCategTwoSelectId: 'showCategTwoIdList',
            }, {
                ecCategOneSelectId: {
                    tips: "-前台一级分类-",
                    isReload: true,
                },
                ecCategTwoSelectId: {
                    tips: "-前台二级分类-",
                    events: {
                        changed(values) {
                            json.vo.showCategTwoIdList = values;
                            zmnOmsSelect.reloadXmSelect('showProductIdList', {
                                remote: {
                                    events: {
                                        extendParams: function() {
                                            let data = {
                                                servCategoryId: json.vo.servCategId,
                                                categIds: json.vo.showCategTwoIdList
                                            }
                                            return { body: data };
                                        }
                                    }
                                }
                            });
                        }
                    }

                }
            });
        }

        // 前台产品
        if (checkExistId('showProductIdList')) {
            zmnOmsSelect.selectProductList('showProductIdList', {
                tips: "-选择前台产品-",
                remote: {
                    events: {
                        extendParams: function() {
                            return {
                                showType: 2
                            };
                        }
                    }
                }
            });
        }

        // 后台一二级分类
        if (checkExistId('categOneIdList')) {
            zmnSelect.selectlErpProdCategories({
                erpCategOneSelectId: 'categOneIdList',
                erpCategTwoSelectId: 'categTwoIdList',
            }, {
                erpCategOneSelectId: {
                    tips: "-后台一级分类-",
                    isReload: true,
                },
                erpCategTwoSelectId: {
                    tips: "-后台二级分类-",
                    events: {
                        changed(values) {
                            json.vo.categTwoIdList = values;
                            zmnOmsSelect.reloadXmSelect('productIdList', {
                                remote: {
                                    events: {
                                        extendParams: function() {
                                            let data = {
                                                servCategoryId: json.vo.servCategId,
                                                categIds: json.vo.categTwoIdList,
                                            }
                                            return { body: data };
                                        }
                                    }
                                }
                            });
                        }
                    }
                }
            });
        }

        // 后台产品
        if (checkExistId('productIdList')) {
            zmnOmsSelect.selectProductList('productIdList', {
                tips: "-选择后台产品-",
                remote: {
                    events: {
                        extendParams: function() {
                            return {
                                showType: 1
                            };
                        }
                    }
                }
            });
        }

        // 工程师
        if (checkExistId('masterId')) {
            zmnSelect.searchEngineer('masterId', {
                isRadio: true,
                remote: {
                    limitPermit: json.vo.orgLimitPermit,
                    events: {
                        extendParams: function() {
                            return {
                                plat: plat,
                                companyId: json.vo.companyId,
                                spCompanyId: json.vo.spCompanyId,
                            }
                        }
                    }
                },
                events: {
                    changed: function(values) {}
                }
            });
        }

        // 从工程师
        if (checkExistId('multiMasterId')) {
            zmnSelect.searchEngineer('multiMasterId', {
                isRadio: true,
                remote: {
                    limitPermit: json.vo.orgLimitPermit,
                    events: {
                        extendParams: function() {
                            return {
                                plat: plat,
                                companyId: json.vo.companyId,
                                spCompanyId: json.vo.spCompanyId,
                            }
                        }
                    }
                },
                events: {
                    changed: function(values) {}
                }
            });
        }

        // 责任工程师
        if (checkExistId('cancelLiableMasterId')) {
            zmnSelect.searchEngineer('cancelLiableMasterId', {
                isRadio: true,
                remote: {
                    limitPermit: json.vo.orgLimitPermit,
                    events: {
                        extendParams: function() {
                            return {
                                plat: plat,
                                companyId: json.vo.companyId,
                                spCompanyId: json.vo.spCompanyId,
                            }
                        }
                    }
                },
                events: {
                    changed: function(values) {}
                }
            });
        }

        // 加单工程师
        if (checkExistId('recommenderId')) {
            zmnSelect.searchEngineer('recommenderId', {
                isRadio: true,
                remote: {
                    limitPermit: json.vo.orgLimitPermit,
                    events: {
                        extendParams: function() {
                            return {
                                plat: plat,
                                companyId: json.vo.companyId,
                                spCompanyId: json.vo.spCompanyId,
                            }
                        }
                    }
                }
            });
        }

        // 工程师主管
        if (checkExistId('masterSupervisorId')) {
            zmnSelect.searchEngineerSupervisor('masterSupervisorId', {
                isRadio: true,
                remote: {
                    limitPermit: json.vo.orgLimitPermit,
                    events: {
                        extendParams: function() {
                            return {
                                plat: plat,
                            }
                        }
                    }
                },
                events: {
                    changed: function(values) {}
                }
            });
        }

        // 下单渠道
        if (checkExistId('channelTwoIdList')) {
            zmnSelect.selectlChannels({
                channelOneSelectId: 'channelTwoIdList',
                channelTwoSelectId: 'channelIdList',
            }, {
                channelOneSelectId: {
                    remote: {
                        limitPermit: json.vo.channelLimitPermit,
                    },
                    events: {
                        changed: function(values) {
                            if (values.length == 0) {
                                zmnSelect.reloadXmSelect('channelIdList', {
                                    isReload: true
                                });
                            }
                        }
                    }
                },
                channelTwoSelectId: {
                    remote: {
                        limitPermit: json.vo.channelLimitPermit,
                        // url: ZMN_CONFIG.BASE_URL.GATEWAY_API_BASE + '/plat/sapi/channel/listChannelVtByQuery',
                        // events: {
                        //     extendParams: function (prevValues, newExtendParams) {
                        //         let params = $.extend(true, {}, {
                        //             "rank": 2,
                        //             parentId: zmnUtil.isArray(prevValues) && prevValues.length > 0 ? prevValues[0] : null,
                        //         }, newExtendParams);
                        //
                        //         return {
                        //             searchQuery: params
                        //         };
                        //     }
                        // }
                    }
                }
            });
            zmnSelect.reloadXmSelect('channelIdList', {
                isReload: true
            });
        } else if (checkExistId('channelIdList')) {
            zmnSelect.searchChannel('channelIdList', {
                remote: {
                    limitPermit: json.vo.channelLimitPermit,
                    events: {
                        extendParams: function() {
                            return {
                                "rank": 2, //渠道层级：Integer类型；1-查询一级渠道，2-查询二级渠道,null不限
                            }
                        }
                    }
                },
                events: {
                    changed: function(values) {}
                }
            });
        }

        // 来源下单渠道
        if (checkExistId('sourceChannelTwoIdList')) {
            zmnSelect.selectlChannels({
                channelOneSelectId: 'sourceChannelTwoIdList',
                channelTwoSelectId: 'sourceChannelIdList',
            }, {
                channelOneSelectId: {
                    remote: {
                        limitPermit: json.vo.channelLimitPermit,
                    },
                    events: {
                        changed: function(values) {
                            if (values.length == 0) {
                                zmnSelect.reloadXmSelect('sourceChannelIdList', {
                                    isReload: true
                                });
                            }
                        }
                    }
                },
                channelTwoSelectId: {
                    remote: {
                        limitPermit: json.vo.channelLimitPermit,
                        // url: ZMN_CONFIG.BASE_URL.GATEWAY_API_BASE + '/plat/sapi/channel/listChannelVtByQuery',
                        // events: {
                        //     extendParams: function (prevValues, newExtendParams) {
                        //         let params = $.extend(true, {}, {
                        //             "rank": 2,
                        //             parentId: zmnUtil.isArray(prevValues) && prevValues.length > 0 ? prevValues[0] : null,
                        //         }, newExtendParams);
                        //
                        //         return {
                        //             searchQuery: params
                        //         };
                        //     }
                        // }
                    }
                }
            });

            zmnSelect.reloadXmSelect('sourceChannelIdList', {
                isReload: true
            });
        } else if (checkExistId('sourceChannelIdList')) {
            zmnSelect.searchChannel('sourceChannelIdList', {
                remote: {
                    limitPermit: json.vo.channelLimitPermit,
                    events: {
                        extendParams: function() {
                            return {
                                "rank": 2, //渠道层级：Integer类型；1-查询一级渠道，2-查询二级渠道,null不限
                            }
                        }
                    }
                },
                events: {
                    changed: function(values) {}
                }
            });
        }

        // 网格ID
        if (checkExistId('gridIdList')) {
            zmnOmsSelect.selectGmsGrid('gridIdList', {
                tips: "全部", //默认提示
                page: {
                    enable: true,
                    remote: true,
                    pageSize: 50
                },
                remote: {
                    events: {
                        extendParams: function() {
                            return {
                                cityIdList: checkExistId('cityIdList') ? zmnSelect.getSelectedValue('cityIdList') : null
                            }
                        }
                    }
                }
            });
        }

        // 工单结果
        zmnOmsSelect.selectWorkResultStatus('workResultStatus');
        // 工单状态
        zmnOmsSelect.selectWorkStatus('workStatusList');
        // 工单类型
        zmnOmsSelect.selectWorkType('workTypeList');
        // 上门类型
        zmnOmsSelect.selectVisitType('visitType');
        // 上门状态
        zmnOmsSelect.selectVisitStatus('visitStatus');
        // 快递状态
        zmnOmsSelect.selectPostStatus('orderPostStatusList');
        // 多工程师
        zmnOmsSelect.selectHasOrNoStatus('multiMaster');
        // 重复
        zmnOmsSelect.selectRepeatOrNoStatus('duplicate');
        // 工单操作类型
        zmnOmsSelect.selectWorkOperateType('operate_operateType');
        // 工单标记
        zmnOmsSelect.selectOrderWorkTagList('tagIdList');
        // 用户层级
        zmnOmsSelect.selectUserLevelList('userLevel');
        // 品牌
        zmnOmsSelect.selectBrandList('brandId');
        // 支付状态
        zmnOmsSelect.selectOrderPayStatus('payStatusList');
        // 退款审核状态
        zmnOmsSelect.selectRefundWorkReviewStatus('refundWorkReviewStatusList');
        // 赔偿审核状态
        zmnOmsSelect.selectCompensateWorkReviewStatusList('compensateWorkReviewStatusList');
        // 配件报销
        zmnOmsSelect.selectPartReimburseStatusList('partReimburseStatus');
        // 参与报价人类型
        zmnOmsSelect.selectPartakeQuotationType('partakeQuotationTypeList');
        // 最终报价人类型
        zmnOmsSelect.selectQuotationType('quotationType');
        // 退款方式
        zmnOmsSelect.selectRefundType('refundType');
        // 取消人类型
        if (checkExistId('cancelerTypeList')) {
            zmnSelect.selectOperatorType('cancelerTypeList');
        }
        // 取消缘由
        zmnOmsSelect.selectCancelReasonList('failMapIdList', {
            remote: {
                events: {
                    extendParams: function() {
                        return {
                            bizType: json.vo.bizType,
                        }
                    }
                }
            }
        });
        // 取消tag-工单结果
        zmnOmsSelect.selectWorkCancelResultStatus('workCancelResultStatus');
        // 取消tag-工单状态
        zmnOmsSelect.selectWorkCancelStatus('workCancelStatusList');

        // 操作员
        if (checkExistId('operate_operatorId')) {
            zmnSelect.searchStaff('operate_operatorId', {
                isRadio: true,
                remote: {
                    limitPermit: json.vo.orgLimitPermit,
                    events: {
                        extendParams: function() {
                            return {
                                companyIdList: json.vo.companyIdList,
                                // deptIdList: dpermitDeptIdList && dpermitDeptIdList.length > 0 ? dpermitDeptIdList : null,
                                // orgIdList: dpermitOrgIdList && dpermitOrgIdList.length > 0 ? dpermitOrgIdList : null,
                                //status: 2,
                            }
                        }
                    }
                }
            });
        }

        // 取消人
        if (checkExistId('cancelerId')) {
            zmnSelect.searchStaff('cancelerId', {
                isRadio: true,
                remote: {
                    limitPermit: json.vo.orgLimitPermit,
                    events: {
                        extendParams: function() {
                            return {
                                companyIdList: json.vo.companyIdList,
                                // deptIdList: dpermitDeptIdList && dpermitDeptIdList.length > 0 ? dpermitDeptIdList : null,
                                // orgIdList: dpermitOrgIdList && dpermitOrgIdList.length > 0 ? dpermitOrgIdList : null,
                                //status: 2,
                            }
                        }
                    }
                }
            });
        }

    }

    /**
     * 初始化页面表单验证器
     */
    function initFormVerify() {
        form.verify({
            channelListStr: function(value) {
                value = value == null ? '' : value;
                value = $.trim(value);
                if (/[^0-9\,\，]/.test(value)) {
                    return '只能输入以逗号分隔的渠道 id';
                }
                return;
            }
        });
    }

    // 初始化业务类型和跟单内容
    function initMultSelectTrackType() {
        //初始化业务类型
        var $bizType = $('select[name="bizType"]');
        if (plat == platMark.ZMN || plat == platMark.YBWX || plat == platMark.CNHB) {
            $bizType.val(1);
        } else if (plat == platMark.YEYX) {
            $bizType.val(2);
        }
        form.render('select');

        var bizType = $bizType.val();
        setTimeout(function() {
            $bizType.next().find('.layui-anim').children('dd[lay-value="' + bizType + '"]').click();
        }, 2000);

    }

    /**
     * 初始化查询条件
     */
    function initQueryParams() {
        if (!defaultQuery) {
            return;
        }

        tableConfig.defaultParams = {};

        // 用户id
        if (defaultQuery.userId) {
            tableConfig.defaultParams['userId'] = defaultQuery.userId;
            tableConfig.initialSearch = true;
        }

        // 工单号
        if (defaultQuery.id) {
            tableConfig.defaultParams['code'] = defaultQuery.id;
            tableConfig.initialSearch = true;
        }

        // 手机号
        if (defaultQuery.concatPhone) {
            tableConfig.defaultParams['concatPhone'] = defaultQuery.concatPhone;
            tableConfig.initialSearch = true;
        }
        if (defaultQuery.cryptoPhone) {
            tableConfig.defaultParams['cryptoPhone'] = defaultQuery.cryptoPhone;
            tableConfig.initialSearch = true;
        }

        // 服务分类
        if (defaultQuery.serviceCategoryId) {
            tableConfig.defaultParams['serviceCategoryId'] = defaultQuery.serviceCategoryId;
            tableConfig.initialSearch = true;
        }

        // 工单结果状态
        if (defaultQuery.workResultStatus) {
            tableConfig.defaultParams['workResultStatus'] = defaultQuery.workResultStatus;
            tableConfig.initialSearch = true;
        }

        // 工单号
        if (defaultQuery.orderId) {
            tableConfig.defaultParams['orderId'] = defaultQuery.orderId;
            tableConfig.initialSearch = true;
        }

        // 工单类型
        if (defaultQuery.singleWorkType) {
            tableConfig.defaultParams['singleWorkType'] = defaultQuery.singleWorkType;
            tableConfig.initialSearch = true;
        }
    }

    /**
     * 初始化页面
     */
    function initPage() {

        // 初始化页面数据
        initEvent();

        // 初始化查询条件
        initQueryParams();

        // 渲染 table
        if (tableConfig.initialSearch) {
            searchForTable(tableConfig.defaultParams);
        } else {
            searchForTable({}, []);
        }

        lazyLoad(function() {
            // 初始化页面所有下拉框
            initAllSelect();

            // 初始化页面所有的日期选择器
            layui.use('laydate', function(laydate) {
                initALLDatePickers(laydate);
            });

            // 初始化表单验证器
            initFormVerify();

            // 初始化业务类型和跟单内容
            initMultSelectTrackType();
        });

        $('body').append('<div class="page-loaded"></div>');
    }

    initPage();

    exports('oms_work_list');
});